package com.bbs.crawl;

import java.sql.Connection;

import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.bbs.bean.ReplyBBS;
import com.bbs.dao.HuiFuDAO;
import com.car.util.DocUtil;

public class ReplyCarwl implements Runnable {
	static Logger logger = Logger.getLogger(ReplyCarwl.class.getName());
	private int hf_yhid;
	private Connection conn;
	HuiFuDAO huiFuDao=new HuiFuDAO(conn);
	@Override
	public void run() {
		startCarwl(this.hf_yhid);
	}

	public void startCarwl(int hf_yhid) {
		int page = getPages(hf_yhid);
		for (int i = 1; i < page + 1; i++) {
			String url = "http://i.service.autohome.com.cn/clubapp/OtherReply-" + hf_yhid + "-" + i + ".html";
			Document doc = DocUtil.getDoc(url);
			Elements eles1 = doc.select("div.m_t15 tr:not(.kill)");
			for (Element ele : eles1) {
				try {
					String hf_bt = ele.select("div.pr span.rUser_rc a").get(0).text();
					int hf_hfuid = Integer.parseInt(ele.select("div.pr span.rUser_rc a").get(1).attr("href"));
					Element e = ele.select("div.pr span.rUser_rc").get(2);
					String link = e.select("a:not(.next)").attr("href");
					int hf_clubid = Integer.parseInt(link.split("-")[2]);
					int hf_bbsid = Integer.parseInt(link.split("-")[3]);
					int hf_lc = Integer.parseInt(link.split("#")[1]);
					String hf_nr = e.select("a:not(.next)").text();
					String hf_time = ele.select("td.txtCen").get(1).text();
					ReplyBBS replyBBS = new ReplyBBS(hf_yhid, hf_clubid, hf_bbsid, hf_bt, hf_nr, hf_hfuid, hf_lc,
							hf_time);
					
					huiFuDao.insertHuiFu(replyBBS);
				} catch (Exception e) {
				}

			}

		}
	}

	public int getPages(int hf_yhid) {
		int page = 1;
		String url = "http://i.service.autohome.com.cn/clubapp/OtherReply-" + hf_yhid + "-1.html";
		try {
			Document doc = DocUtil.getDoc(url);
			int eles = doc.select("div.paging a").size() - 1;
			page = eles > 0 ? eles : 1;
		} catch (Exception e) {
		}

		return page;
	}

	public ReplyCarwl(int hf_yhid, Connection conn) {
		super();
		this.hf_yhid = hf_yhid;
		this.conn = conn;
	}


}
